package jzOffer;

import java.util.LinkedList;
import java.util.Queue;

public class Num37 {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root==null) return "[]";
        StringBuilder sb=new StringBuilder("[");
        Queue<TreeNode> q=new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
            TreeNode node=q.poll();
            if(node==null){
                sb.append("null,");
            } else{
                sb.append(node.val+",");
                q.add(node.left);
                q.add(node.right);
            }
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append("]");
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("[]")) return null;
        String[] ch=data.substring(1,data.length()-1).split(",");
        TreeNode root=new TreeNode(Integer.parseInt(ch[0]));
        Queue<TreeNode> q=new LinkedList<>();
        q.add(root);
        int i=1;
        while(!q.isEmpty()){
            TreeNode node=q.poll();
            if(!ch[i].equals("null")){
                node.left=new TreeNode(Integer.parseInt(ch[i]));
                q.add(node.left);
            }
            i++;
            if(!ch[i].equals("null")){
                node.right=new TreeNode(Integer.parseInt(ch[i]));
                q.add(node.right);
            }
            i++;
        }
        return root;
    }
}
